package cn.lg.soar.activiti.controller;

import cn.lg.soar.activiti.api.enums.ResourceTypeEnum;
import cn.lg.soar.activiti.service.ProcessService;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.util.FileUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.util.Map;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@RestController
@RequestMapping("/process")
@Tag(description = "process", name = "process表管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class ProcessController {

	private final ProcessService processService;

	public ProcessController(ProcessService processService) {
		this.processService = processService;
	}

	@GetMapping
	@Operation(summary = "条件查询", description = "条件查询")
	public HttpResult list(@RequestParam Map<String, Object> params) {
		return HttpResult.data(processService.getProcessByPage(params));
	}

	@GetMapping(value = "/resource/{proInsId}/{procDefId}/{resType}")
	@Operation(summary = "查询", description = "查询")
	public ResponseEntity resourceRead(@PathVariable String procDefId, @PathVariable String proInsId,
			@PathVariable String resType) {
		HttpHeaders headers = new HttpHeaders();

		if (ResourceTypeEnum.XML.getType().equals(resType)) {
			headers.setContentType(MediaType.APPLICATION_XML);
		}
		else {
			headers.setContentType(MediaType.IMAGE_PNG);
		}

		InputStream resourceAsStream = processService.readResource(procDefId, proInsId, resType);
		return new ResponseEntity(FileUtil.readBytes(resourceAsStream), headers, HttpStatus.CREATED);
	}

	@PutMapping("/status/{procDefId}/{status}")
	@Operation(summary = "修改", description = "修改")
	public HttpResult updateState(@PathVariable String procDefId, @PathVariable String status) {
		return HttpResult.data(processService.updateStatus(status, procDefId));
	}

	@DeleteMapping
	@Operation(summary = "删除流程", description = "删除流程")
	public HttpResult deleteProcIns(@RequestBody String[] ids) {
		return HttpResult.data(processService.removeProcIns(ids));
	}

}
